#include "sslclient.hpp"
#include<iostream>
#include<string.h>
#include<thread>

void timeout(SSLClient* client,void* arg){
	printf("time out!\n");
	*(bool*)arg=true;
}

bool onlogin(SSLClient* client,void* arg){
	if(*(bool*)arg){
		printf("logged!\n");
		return true;
	}
	printf("log error!\n");
	return true;
}
static bool running=true;
void updatestatus(SSLClient* client,size_t sleeptime){
	while(running){
		client->update();
		std::this_thread::sleep_for(std::chrono::milliseconds(sleeptime));
	}
}
int main(){
	bool neterr=false;
	static const size_t beat=0;
	if(SSLClient::openlib()){
		SSLClient* client=new SSLClient({(char*)&beat,1,SSLClient::emptysendback},timeout,&neterr);
		if(!client->connecthost("127.0.0.1",8888)){
			std::string temp;
			bool logged;
			std::thread th(updatestatus,client,1000/30);
			while(!neterr){
				std::getline(std::cin,temp,'\n');
				if(temp.empty())continue;
				auto f=temp.find(' ');
				if(f==std::string::npos){
					printf("command error\n");
					continue;
				}
				auto cmd=temp.substr(0,f++);
				if(cmd=="login"){
					auto pos=temp.find(' ',f);
					if(pos==std::string::npos){
						printf("no account given\n");
						continue;
					}
					auto len=pos-f;
					if(len>4){
						printf("account exceed maxlength:4\n");
						continue;
					}
					char buffer[21];
					buffer[0]=1;
					strncpy(buffer+1,temp.substr(f,len).c_str(),4);
					strncpy(buffer+5,temp.substr(pos+1).c_str(),16);
					client->senddata({buffer,21,SSLClient::emptysendback});
					client->recvdata({(char*)&logged,1,onlogin,&logged});
					continue;
				}
				if(cmd=="exit"){
					running=false;
					th.join();
					delete client;
					return 0;
				}
				printf("command error\n");
				continue;
			}
			printf("connection error\n");
		}
		delete client;
		SSLClient::closelib();
	}
	return -1;
}